<template>
  <div class="schedule-container">
    <!-- 控制面板 -->
    <ScheduleControlPanel
        :selected-term="selectedTerm"
        :term-options="termOptions"
        :selected-week="selectedWeek"
        :week-options="weekOptions"
        :has-selected-course="!!selectedCourse"
        @update:selected-term="selectedTerm = $event"
        @update:selected-week="selectedWeek = $event"
    />

    <!-- 课程表 -->
    <ScheduleTableContent
        :week-days="weekDays"
        :lessons="lessons"
        :courses="courses"
        :selected-course="selectedCourse"
        @select-course="selectCourse"
    />
  </div>
</template>

<script setup>
import {ref ,onMounted,watch} from 'vue';
import {ElMessage} from 'element-plus';

import ScheduleControlPanel from './components/ScheduleControlPanel.vue';
import ScheduleTableContent from './components/ScheduleTableContent.vue';
import {
  fetchStudentScheduleByDateRange,
  fetchAllTerms,
  fetchTermWeeks,
  fetchCourseCategories,
} from "@/api/student.js";
import {
  transformToNestedSchedule,
  transformTermData,
  transformWeekData
} from '@/utils/scheduleTransformer.js';

const selectedTerm = ref('');
const termOptions = ref([]);

const selectedWeek = ref('');
const weekOptions = ref([]);
const courseCategories = ref([]);
// 课程表数据
const weekDays = ['周一', '周二', '周三', '周四', '周五'];
const lessons = [
  {time: '08:00-08:45'},
  {time: '08:55-09:40'},
  {time: '10:00-10:45'},
  {time: '10:55-11:40'},
  {time: '14:00-14:45'},
  {time: '14:55-15:40'},
  {time: '16:00-16:45'}
];

// 模拟课程数据
const courses = ref({});

// 监听选择变化
watch([ selectedTerm, selectedWeek], ([ newTerm, newWeek], [oldClass, oldTerm, oldWeek]) => {
  // 只有当所有必要参数都有值时才加载数据
  if ( newTerm && newWeek) {
    loadScheduleData();
  }
}, { deep: true });

// 专门用于加载课程表数据的函数
const loadScheduleData = async () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    const userInfo = JSON.parse(userInfoStr)

    if ( !selectedTerm.value || !selectedWeek.value) {
      console.log('等待选择完整参数');
      return;
    }

    // 根据选中的周次value找到对应的周次数据
    const selectedWeekData = weekOptions.value.find(week => week.value == selectedWeek.value);

    if (!selectedWeekData) {
      ElMessage.error('未找到对应的周次数据');
      return;
    }

    // 使用新的API：按日期范围查询
    const response = await fetchStudentScheduleByDateRange(
        userInfo.classId,
        selectedWeekData.startDate,  // 使用周次的开始日期
        selectedWeekData.endDate     // 使用周次的结束日期
    );;
    courses.value = transformToNestedSchedule(response.data);
    ElMessage.success('课程表加载成功');

  } catch (err) {
    console.error('课程表加载失败:', err);
    ElMessage.error('课程表加载失败: ' + (err.response?.data?.message || err.message));
  }
};


const loadData = async () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')

    // 只并行请求班级、学期、周次选项数据
    const [ terms, weeks,categories] = await Promise.all([
      fetchAllTerms(),
      fetchTermWeeks(1), // 这里可能需要根据学期ID获取周次
      fetchCourseCategories()
    ]);

    // 处理响应数据
    termOptions.value = transformTermData(terms.data);
    weekOptions.value = transformWeekData(weeks.data);
    courseCategories.value = categories.data;

    if (termOptions.value.length > 0) {
      selectedTerm.value = termOptions.value[0].value;
    }
    if (weekOptions.value.length > 0) {
      selectedWeek.value = weekOptions.value[0].value;
    }

  } catch (err) {
    ElMessage.error('选项数据加载失败:' + err.message);
  }
};


onMounted(()=>{
  loadData()
})

// 选中课程状态
const selectedCourse = ref(null);

// 获取课程信息
const getCourse = (day, time) => {
  return courses.value[day]?.[time] || null;
};

// 选择课程
const selectCourse = (day, time) => {
  const course = getCourse(day, time);
  if (course) {
    selectedCourse.value = {
      ...course,
      day,
      time,
      lessonIndex: lessons.findIndex(l => l.time === time)
    };
  } else {
    selectedCourse.value = null;
  }
};



</script>

<style scoped>
.schedule-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}


.schedule-table th,
.schedule-table td {
  border: 1px solid #ebeef5;
  padding: 8px;
  text-align: center;
}

.schedule-table th {
  background-color: #f5f7fa;
  font-weight: bold;
  color: #303133;
}


.course-details h4 {
  margin-top: 0;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
  margin-bottom: 10px;
}

</style>

